﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;

namespace WebAPI_Demo.Filter
{
    public class RateLimitActionFilter : IActionFilter
    {
        private readonly IMemoryCache memCache;

        public RateLimitActionFilter(IMemoryCache memCache)
        {
            this.memCache = memCache;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //LogHelper.Info("OnActionExecuted");
            //执行方法后执行这
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            Console.WriteLine("RateLimitActionFilter 执行action前");
            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();
            string cacheKey = $"lastvisittick_{ip}";
            long? lastVisit = memCache.Get<long?>(cacheKey);
            if (lastVisit == null || Environment.TickCount64 - lastVisit > 1000) // Environment.TickCount64 系统时间
            {
                memCache.Set(cacheKey, Environment.TickCount64, TimeSpan.FromSeconds(10));//避免长期不访问的用户，占据缓存的内存
                Console.WriteLine("RateLimitActionFilter 执行action后");
            }
            else
            {
                ObjectResult result = new ObjectResult("访问太频繁")
                {
                    StatusCode = 429
                };
                context.Result = result;
            }
        }
    }
}
